import { _decorator, Component, Label, Node } from 'cc';
import { Building, EventOper } from '../entity/Buildings';
import { UserInfo } from '../common/UserInfo';
import { Utils } from '../common/Utils';
import { UIManager } from '../common/UIManager';
import { PrefabEnum } from '../common/PrefabEnum';
import VillageApi from '../api/VillageApi';
const { ccclass, property } = _decorator;

@ccclass('WorkerItem')
export class WorkerItem extends Component {
    @property(Label)
    title: Label
    @property(Label)
    time: Label
    @property(Node)
    speed: Node

    offTime: number = 0
    buildData:Building

    start() {
        this.speed.on(Node.EventType.TOUCH_END, this.onSpeed, this)
    }

    setData(build: Building) {
        this.buildData = build

        this.title.string = build.name
        this.time.string = build.desc

        let event = build.getBuildingEvent()
        if (event) {
            let eStartTime = event.eStartTime
            this.offTime = eStartTime - Math.floor(UserInfo.instance.serverTime / 1000)
            if (this.offTime <= 0) {
                return
            }

            this.time.string = '剩余时间：' + Utils.secondToStr(this.offTime)
            this.schedule(this.updateTime, 1, this.offTime - 1)

            this.speed.active = true
        } else {
            this.speed.active = false
        }
    }

    updateTime(){
        this.offTime--
        this.time.string ='剩余时间：' +  Utils.secondToStr(this.offTime)

        if (this.offTime <= 0) {
            // 倒计时完成
            // 清除事件，刷新页面
            UserInfo.instance.refreshVillageDetail()
            UIManager.instance.closeUI(PrefabEnum.WorkerList)
        }
    }

    async onSpeed() {
        let param = {
            ac: EventOper.CANCEL,
            eid: this.buildData.getBuildingEvent().eHandle
       }
       if (this.buildData.isBuilding) {
            param.ac = EventOper.SPEED_BUILD
       }
       if (this.buildData.isRemoving) {
            param.ac = EventOper.SPEED_REMOVE
       }
       await UIManager.instance.showLoading()
       let res = await VillageApi.eventOper(param)
       UIManager.instance.closeLoading()
       console.log(`速拆与速建ac =${param.ac} ,del =${param.eid} `, res)

       UserInfo.instance.refreshVillageDetail()
       UIManager.instance.closeUI(PrefabEnum.WorkerList)
    }
}


